<template>
    <div>
        <el-page-header @back="$router.back(-1)" :content="$route.meta.title" class="headerBack"></el-page-header>
        <div class="container">
            <el-card shadow="hover" style="padding:0">
                <!-- 操作按钮 -->
                <el-card class="operate_container" shadow="never">
                    <div class="wrapper">
                        <div><i class="el-icon-tickets" style="margin-right: 10px;"></i>数据列表</div>
                        <div>
                            <el-button type="primary" :icon="!toggleCheck?'el-icon-check':'el-icon-close'" @click="handleCheckAll" size="medium">{{!toggleCheck?'全选':'不选'}}</el-button>
                            <el-button type="primary" icon="el-icon-success" @click="handleSetPermission" :loading="submitLoading" size="medium">保存</el-button>
                        </div>
                    </div>
                </el-card>

                <!-- 表格 -->
                <el-table
                    ref="table"
                    size="small"
                    empty-text="暂无数据"
                    element-loading-text="给我一点时间"
                    fit
                    stripe
                    border
                    highlight-current-row
                    default-expand-all
                    v-loading="loading"
                    row-key="id"
                    :indent="30"
                    :data="data"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                    :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                >
                    <el-table-column type="index" width="55" align="center"></el-table-column>

                    <el-table-column label="名称" prop="name" align="left" width="250"/>

                    <el-table-column label="权限" align="left">
                        <template slot-scope="scope" v-if="scope.row.permission">
                            
                            <el-checkbox-group v-model="permissionCheckList">
                                <el-checkbox :label="'checkAll-'+scope.row.id" @change="handleCheckAllChange">全选</el-checkbox>
                                <el-checkbox v-for="item in scope.row.permission"
                                    :label="`${scope.row.id}-${item.id}`" 
                                    :key="`${scope.row.id}-${item.id}`">
                                    {{ item.name }}
                                </el-checkbox>
                            </el-checkbox-group>

                        </template>
                    </el-table-column>

                </el-table>
            </el-card>
        </div>
    </div>
</template>

<script>
import { listWithTreeOnPermission } from "@/api/admin/sysmenu"
import { saveRolePermission, getPermissionByRoleId } from "@/api/admin/sysrole"
import { list, findPermissionByMenuId } from "@/api/admin/syspermission"
import { mapMutations } from 'vuex'
export default {
    data() {
        return {
            loading: true,
            submitLoading: false,
            total: 0,
            data: [],
            toggleCheck: false,
            allPermissionList: [],      // 所有的权限
            permissionCheckList: [],    // 选中的权限
            /**
             * 接受父页面传参，参数如下：
             * id
             */
        }
    },
    mounted() {
        this.getTreeGrid()
    },
    methods: {
        handleCheckAll() { // 全部全选
            if(!this.toggleCheck) {
                this.permissionCheckList = []
                for(let item of this.allPermissionList) {
                    this.permissionCheckList.push(item.menuId+'-'+item.id)
                }
            } else {
                this.permissionCheckList = []
            }
            this.toggleCheck = !this.toggleCheck
        },
        handleCheckAllChange(checked, e) { // 全选
            const menuId = e.target.getAttribute('value').split("-")[1]

            //获取当前选中菜单的权限
            let nodePermissions = this.getMenuNodePermission(menuId)

            if(checked) { //全选
                let permissions = []
                for(let item of nodePermissions) {
                    permissions.push(menuId+'-'+item.id)
                }
                //将当前选中的权限与已选的权限去重
                this.permissionCheckList = Array.from(new Set([...this.permissionCheckList, ...permissions]))
            } else { // 全不选
                let tempPermission = []
                for (let item of nodePermissions) {
                    tempPermission.push(menuId+'-'+item.id)
                }
                for (let item of tempPermission) {
                    //获取索引
                    let index = this.permissionCheckList.findIndex(function (val) {
                        return val == item
                    })
                    if (index != -1) {
                        //删除元素
                        this.permissionCheckList.splice(index, 1)
                    }
                }
            }
        },
        handleFilterPermission() { //找出全选复选框的索引，删除
            let count = 0;
            for(let item of this.permissionCheckList) {
                const split = item.split('-')
                if(split[0] === 'checkAll') {
                    count++;
                }
            }
            for(let i=0; i<count; i++) {
                let index = this.permissionCheckList.findIndex((value, index, arr) => {
                    const split = value.split('-')
                    return split[0] === 'checkAll'
                })
                this.permissionCheckList.splice(index, 1)
            }
        },
        getAllPermission() { // 加载所有权限
            list().then(res => {
                this.allPermissionList = res.data
            })
        },
        getMenuNodePermission(menuId) { // 根据菜单ID获取对应的权限
            let nodePermission = this.allPermissionList.filter(function (item, index, array) {
                return item.menuId == menuId
            })
            return nodePermission
        },
        getTreeGrid() { // 加载菜单表格
            listWithTreeOnPermission().then(res => {
                if (this.ResultMessage(res, false)) {
                    this.data = res.data
                    this.loading = false
                } else {
                    this.loading = false
                }
            }).then(() => {
                this.getAllPermission()
            }).then(() => {
                this.getRolePermission();
            }).catch(error => {
                this.loading = false
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            })
        },
        getRolePermission() { //根据角色ID获取对应的权限
            getPermissionByRoleId(this.$route.query.id).then(res => {
                this.permissionCheckList = []
                if(res.data) {
                    for(let item of res.data) {
                        this.permissionCheckList.push(item.menuId+'-'+item.permissionId)
                    }
                }
            })
        },
        
        handleSetPermission() { //设置角色菜单权限
            if(this.permissionCheckList.length > 0) {
                this.submitLoading = true
                this.handleFilterPermission();
                let data = {"roleId": this.$route.query.id, "permissions": this.permissionCheckList}
                saveRolePermission(data).then(res => {
                    if (this.ResultMessage(res)) {
                        this.$router.back(-1)
                        this.submitLoading = false
                    } else {
                        this.submitLoading = false
                    }
                }).catch(error => {
                    this.submitLoading = false
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            } else {
                this.$notify({ title: '提示', message: '请选择菜单权限', type: 'info' });
            }
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>